# Create your views here.
import json
import re

from QQLoginTool.QQtool import OAuthQQ
from django.contrib.auth import login
from django.http import JsonResponse
from django.views import View

from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from meiduo_mall import settings
from utils.carts import merge_cart_cookie_to_redis


class QQLoginURLView(View):

    def get(self, request):
        # 1.生成实例对象，调用settings中的参数
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='xxxxx')
        # 2.调用对象的方法生成跳转链接
        qq_login_url = qq.get_qq_url()
        # 3.返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'login_url': qq_login_url})


class OauthQQView(View):

    def get(self, request):
        # 1.获取code
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        # 2.通过code换取token
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                     client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI,
                     state='xxxxx')
        token = qq.get_access_token(code)
        # 3.通过token换取openid
        openid = qq.get_open_id(token)
        # 4.通过openid进行查询
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 5.若不存在，说明需要进行绑定
            from apps.oauth.utils import generic_openid
            access_token = generic_openid(openid)
            response = JsonResponse({'code': 400, 'access_token': access_token})
            return response
        else:
            login(request, qquser.user)
            response = JsonResponse({'code': 0, 'errmsg': 'ok'})
            response.set_cookie('username', qquser.user.username)
            response = merge_cart_cookie_to_redis(request, qquser.user, response)
            return response

    def post(self, request):
        # 1.获取请求参数
        data = json.loads(request.body)
        mobile = data.get('mobile')
        password = data.get('password')
        sms_code_client = data.get('sms_code')
        access_token = data.get('access_token')
        # 2.验证数据
        if not all([mobile, password, sms_code_client, access_token]):
            return JsonResponse({'code': 400, 'errmsg': '参数不全'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 400, 'errmsg': '手机号不符合要求'})
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return JsonResponse({'code': 400, 'errmsg': '密码不符合要求'})
        # 3.验证短信验证码
        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        sms_code_server = redis_cli.get(mobile)
        if sms_code_server is None:
            return JsonResponse({'code': 400, 'errmsg': '验证码失效'})
        if sms_code_client != sms_code_server.decode():
            return JsonResponse({'code': 400, 'errmsg': '验证码错误'})
        # 4.保存数据
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            if not user.check_password(password):
                return JsonResponse({'code': 400, 'errmsg': '账号或密码错误'})
        # 解密token
        from apps.oauth.utils import check_access_token
        openid = check_access_token(access_token)
        if openid is None:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        OAuthQQUser.objects.create(user=user, openid=openid)

        # 5.状态保持
        login(request, user)
        # 6.返回响应
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username)
        return response


#############itsdangerous的基本使用################

# 1.导入类
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer

# 2.创建类实例
s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)

# 3.加密数据
token = s.dumps({'openid': '1234567890'})
# b'eyJhbGciOiJIUzUxMiIsImlhdCI6MTcyMjE0ODA0OSwiZXhwIjoxNzIyMTUxNjQ5fQ.eyJvcGVuaWQiOiIxMjM0NTY3ODkwIn0.1AKenFuvAjLPbZfKSUpPZ5kkcjpBPX6wX0U2s0NTuveN9tST3HcFs66YrIespHEPiHb2x84vNdcAmc1_VD7B6Q'

# 4.解密数据
token_decode = s.loads(token)
# {'openid': '12345678'}
